setwd("~/Dropbox/trump_voting")
source('code/function.R')
d<- readRDS("data/anes_clean.rds")
d<- as.data.frame(d)
library(tidyverse)
library(questionr)
library(mgcv)
library(reldist)



##establishing quintiles
d_white_2012<- 
    d %>% 
    subset(year==2012 & race=='white') %>% 
    select(racialres, weight)

quartile<- reldist::wtd.quantile(d_white_2012[,1], weight = d_white_2012[,2], q = c(0.25, 0.5, 0.75), na.rm=T)
quintile<- reldist::wtd.quantile(d_white_2012[,1], weight = d_white_2012[,2], q = c(0.2, 0.4, 0.6, 0.8), na.rm=T)

########################White Republicans

set.seed(02138)
white_rep_res<- wrap_func('vote_pres3', 'racialres',
                          d%>% subset(pid3=='rep' & race=='white') %>% filter(year %in% 2012:2020),
                          d %>% filter(year %in% 2012:2020),
                          c(2012, 2016, 2020),
				c('pid3', 'race'), c('rep', 'white'))
# white_rep_res<- wrap_func('vote_pres3', 'racialres', d%>% subset(pid3=='rep' & race=='white'), d, c(1988, 1992, 2000, 2004, 2008, 2012, 2016, 2020),
#                           c('pid3', 'race'), c('rep', 'white'))


#store<- process(white_rep_res)
#figure(store)
# diffs<- year_diffs(white_rep_res,  c(1988, 1992, 2000, 2004, 2008, 2012, 2016, 2020))
diffs<- year_diffs(white_rep_res,  c(2012, 2016, 2020))
g5<- year_graph(diffs, xlab='Racial Resentment')

integ_function(diffs %>%subset(comp=='2016-2012'), quintile)


uncertain_rep<- integ_uncertainty(white_rep_res, quintile, c(2012, 2016))
integ_rep<- apply(uncertain_rep, 2, quantile, c(0.025, 0.5, 0.975))
integ_rep

# Replicates almost perfectly the results in the draft